package com.fulu.game.bi.service.impl.auth.config;

import com.fulu.game.bi.entity.enums.BiAuthcEnum;
import com.fulu.game.bi.service.impl.auth.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
@Slf4j
public class BiShiroConfig {

    @Autowired
    private TokenService tokenService;

    /**
     * 开启cglib代理
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
        creator.setProxyTargetClass(true);
        return creator;
    }

    /**
     * 开启shiro aop注解支持
     * 使用代理方式;所以需要开启代码支持
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * 拦截路径和放行路径
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //添加登录判断拦截器
        HashMap<String, Filter> hashMap = new HashMap<>();
        hashMap.put("acl", biTokenFilter());
        shiroFilterFactoryBean.setFilters(hashMap);

        // 自顶向下过滤
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();

        // 静态资源放行
        filterChainDefinitionMap.put("/static/**", BiAuthcEnum.ANON.getName());
        filterChainDefinitionMap.put("/login", BiAuthcEnum.ANON.getName());
        filterChainDefinitionMap.put("/captcha", BiAuthcEnum.ANON.getName());
        // API接口进行拦截
        filterChainDefinitionMap.put("/api/**/nologin/**", BiAuthcEnum.ANON.getName());
        filterChainDefinitionMap.put("/api/**/console/**", BiAuthcEnum.ANON.getName());
        filterChainDefinitionMap.put("/api/**", "acl");

        //  如果下面的定义与上面冲突，那按照了谁先定义谁说了算
        //  /** 一定要配置在最后
        filterChainDefinitionMap.put("/**", "acl");

        // 将拦截器链设置到shiro中
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        // default "/login.jsp"
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setSuccessUrl("/index");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");

        return shiroFilterFactoryBean;
    }

    public BiTokenFilter biTokenFilter() {
        BiTokenFilter biTokenFilter = new BiTokenFilter();
        biTokenFilter.setTokenService(tokenService);
        return biTokenFilter;
    }


    /**
     * Shiro框架的核心:
     * 管理所有用户的安全操作，并提供安全管理的各种服务。
     */
    @Bean
    public SecurityManager securityManager() {
        BiSecurityManager securityManager = new BiSecurityManager();
        securityManager.setRealm(realm());
        return securityManager;
    }

    /**
     * Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。
     * 当对用户执行认证（登录）和授权（访问控制）验证时，Shiro会从应用配置的Realm中查找用户及其权限信息。
     */
    @Bean
    public BiUsernamePasswordRealm realm() {
        BiUsernamePasswordRealm realm = new BiUsernamePasswordRealm();
        realm.setCredentialsMatcher(credentialsMatcher());
        return realm;
    }

    /**
     * 凭证匹配器
     * （由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了）
     */
    @Bean
    public CredentialsMatcher credentialsMatcher() {
        return new BiUsernamePasswordMatcher();
    }
}
